
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Image,
  Dimensions,TouchableOpacity,FlatList
} from 'react-native';
import RefreshListView, {RefreshState} from 'react-native-refresh-list-view';
import TopBar from '../../bar/TopBar'
import BASEURL from '../../api/api'
import Loading from '../../common/Loading'
import Toast, {DURATION} from 'react-native-easy-toast'
import SearchView from '../../common/SearchView'
import DeviceStorage from '../../common/DeviceStorage'
import {getCurrentDate} from '../../common/common'
import {isIphoneX} from "../../common/Utils";
import Item from './Item'
import History from './History'
import Newest from './Newest'
var {height, width} = Dimensions.get('window');
const dismissKeyboard = require('dismissKeyboard');
var noMore = false;
var currPageNo = 1;
var pageSize = 10;
export default class MonitorInfo extends Component {
  static navigationOptions = ({ navigation }) =>{
    return{
      headerTitle:<TopBar title='监测信息' navigation = {navigation}/>,
      headerLeft:null,
    }
  };
  constructor(props){
    super(props);
    let time = getCurrentDate()
    this.state = ({
      monitor:{},
      loading:true,
      active24:true,
      new:false,
      abnormalList:[],
      hyName:'',
      type:0,//1-数据异常,2-断流,3-未接入,4-正常
      isHistory:false,
      date:time,
      areaCode:'',
      homeSearch:false,
    })
    //console.log(this.props)
  }
  componentWillMount(){
    DeviceStorage.get('areaCode').then((areaCode)=>{
      if(areaCode){
        this.setState({
          areaCode:areaCode
        })
        this.getMonitor(areaCode)
      } 
    })
  }
  onHeaderRefresh = () => {
  }
  onFooterRefreshHome = () => {
    currPageNo++;
    //this.getHistoryList(pageNo);
    this._searchFromServer()
    this.setState({refreshState: RefreshState.FooterRefreshing});
  }
  onFooterRefresh = () => {
    if(noMore){
  		return;
  	}
  	currPageNo++;
    //this.getHistoryList(pageNo);
    this.getMiddleList(currPageNo,this.state.type,false)
    this.setState({refreshState: RefreshState.FooterRefreshing});
  }
  getMonitor(areaCode){
    fetch(BASEURL+'getMonitor?areaCode='+areaCode)
    .then(res=>res.json())
    .then(result=>{
      //console.log('res',result)
      if(result.falg){
        this.setState({
          monitor:result,
          loading:false,
        })
      }
    })
    .catch(err=>{
      this.setState({
        loading:false,
      })
      this.refs.toast.show('获取失败');
    })
  }
  //首页搜索
  _searchFromServer(){
    console.log(BASEURL+'getsearch?hyName='+this.state.hyName+'&areaCode='+this.state.areaCode
    +'&pageNo='+currPageNo+'&pageSize='+pageSize)
    fetch(BASEURL+'getsearch?hyName='+this.state.hyName+'&areaCode='+this.state.areaCode
    +'&pageNo='+currPageNo+'&pageSize='+pageSize)
    .then(res=>res.json())
    .then(result=>{
      console.log('home_result',result)
      if(result.falg){
        let data = result.abnormalList
        data = data.concat(result.disconnectionList)
        data = data.concat(result.unconnectedList)
        data = data.concat(result.normalList)
        if(data.length<pageSize){
          this.setState({
            abnormalList:this.state.abnormalList.concat(data),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            abnormalList:this.state.abnormalList.concat(data),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      } else {
        this.setState({
          loading:false,
          refreshState:RefreshState.Idle,
        })
      }
    })
  }
  //搜索
  searchFlowList(value,homeSearch){
    currPageNo = 1
    noMore = false
    console.log('value',value)
    console.log('type',this.state.type)
    this.setState({
      hyName:value,
      abnormalList:[],
      homeSearch:homeSearch,
    })
    if(this.state.type==0){
      setTimeout(()=>{
        this._searchFromServer()
      },50)
    } else {
      setTimeout(()=>{
        this.getMiddleList(1,this.state.type,true)
      },50)
    }
  }
  //获取4个类型的数据
  getMiddleList(page,type,isSearch){
    currPageNo = page
    //dismissKeyboard();//收起键盘
    this.renderIndexLab()
    //alert(type)
    let loading = currPageNo==1?true:false
    //console.log('type',type)
    this.setState({
      type:type,
      loading:loading,
    })
    var url
    if(type == 1){
      url = "getFlowList?areaCode="+this.state.areaCode
    } else if(type == 2){
      url = 'getStopList?areaCode='+this.state.areaCode
    } else if(type == 3){
      url = 'getNoMonitorList?areaCode='+this.state.areaCode
    } else if(type == 4){
      url = 'getMonitorList?areaCode='+this.state.areaCode
    }
    fetch(BASEURL+url+'&hyName='+this.state.hyName+'&pageNo='+currPageNo+'&pageSize='+pageSize)
    .then(res=>res.json())
    .then(result=>{
      //console.log('result',result)
      if(result.falg){
        let data = []
        if(type == 1) data = result.flowList
        else if(type == 2) data = result.stopList
        else if(type == 3) data = result.empNoMonitorList
        else if(type == 4) data = result.empMonitorList
        // this.setState({
        //   abnormalList:data,
        //   loading:false
        // })
        console.log('type=='+type+',len='+data.length+',pageNo='+currPageNo)
        if(data.length<pageSize){
          noMore = true
          this.setState({
            abnormalList:this.state.abnormalList.concat(data),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            abnormalList:this.state.abnormalList.concat(data),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      } else {
        this.setState({
          loading:false,
          refreshState:RefreshState.Idle,
        })
      }
    })
    .catch((err)=>{
      console.log(err)
    })
  }
  _middleListPress(type){
    currPageNo = 1
    noMore = false
    //this.refs.searchInput.clear()
    // console.log('refs',this.refs)
    // console.log('input',this.refs.searchInput)
    this.setState({
      hyName:'',
      abnormalList:[],
    })
    setTimeout(()=>{
      this.getMiddleList(1,type)
    },50)
  }
  //头部  24  最新 点击事件
  isRecent(bool){
    dismissKeyboard();
    if(bool){ //最新
      this.setState({
        active24:false,
        new:true,
        type:0,
      })
      //this.getFlowList()
    } else {  //24小时
      this.setState({
        active24:true,
        new:false,
        type:0,
        homeSearch:false,
      })
    }
  }
  history(isHistory){
    if(isHistory){
      this.setState({
        isHistory:true,
      })
    } else {
      this.setState({
        isHistory:false,
        loading:false
      })
    }
  }
  _detail(hyCode){
    //console.log('pkId',pkId)
    //console.log('nav',this.props.navigation)
    if(this.props.navigation){
      this.props.navigation.push('monitorDetail',{hyCode})
    }
  }
  _separator = () => {
    return <View style={{height:10,backgroundColor:'#f0f0f0'}}/>;
  }
  _keyExtractor = (item, index) => index.toString();
  _renderHomeItem= ({item,index}) =>{
    return(
      <Item item={item} isHistory={false} navigation={this.props.navigation}/>
    )
  }
  // 4个 FlatList
  _renderFourItem = ({item,index}) =>{
    let type = this.state.type
    let image 
    if(type == 1){
      image = require('../../images/monitor_history_1.png')
    } else if(type == 2){
      image = require('../../images/monitor_history_2.png')
    } else if(type == 3){
      image = require('../../images/monitor_history_3.png')
    } else if(type == 4){
      image = require('../../images/monitor_history_4.png')
    }
    return(
      <TouchableOpacity style={{flexDirection:'row',padding:10,justifyContent:'space-between',alignItems:'center'}} 
          onPress={()=>{this._detail(item.hy_code)}}>
        <View >
          <View style={{flexDirection:'row',marginLeft:5,alignItems:'center',marginBottom:10}}>
            <Image source={image}/>
            <Text style={styles.hyName}>{item.hy_name}</Text>
          </View>
          <Text style={{marginLeft:5,}}>{item.com_locations}</Text>
        </View>
        <View style={{flexDirection:'row',marginRight:10,alignItems:'flex-end'}}>
          <Text style={{fontSize:18,color:'#333'}}>{item.ecology_out_flow}</Text><Text>m³/s</Text>
        </View>
      </TouchableOpacity>
    )
  }
  //渲染中间的视图
  renderMiddleList(){
    let type = this.state.type
    if(this.state.loading){
      return <Loading/>
    } else if(this.state.active24 && this.state.type == 0 && !this.state.homeSearch){
      return(
        <View style={{flex:1}}>
          <View style={styles.searchView}>
            {this.renderIndexLab()}
            <SearchView  placeholder='输入电站名' val={this.state.hyName} 
              search={(val)=>this.searchFlowList(val,true)}/>
          </View>
          <Row title='数据异常' desc='小于最小下泄量' num={this.state.monitor.flowNum} style={{'color':'red'}}
            image={require('../../images/monitor_time_1.png')} press={()=>this._middleListPress(1)}
            />
          <View style={styles.splitView}></View>
          <Row title='断流' desc='超6小时未上报' num={this.state.monitor.stopNum} style={{'color':'orange'}}
            image={require('../../images/monitor_time_2.png')} press={()=>this._middleListPress(2)}
            />
          <View style={styles.splitView}></View>
          <Row title='未接入' desc='未上报过数据' num={this.state.monitor.noMonitorNum} style={{'color':'gray'}}
            image={require('../../images/monitor_time_3.png')} press={()=>this._middleListPress(3)}
            />
          <View style={styles.splitView}></View>
          <Row title='正常' desc='数据正常上报' num={this.state.monitor.nonitorNum} style={{'color':'green'}}
            image={require('../../images/monitor_time_4.png')} press={()=>this._middleListPress(4)}
            />
        </View>
      ) 
    }else if(this.state.active24 && this.state.type == 0 && this.state.homeSearch){
      //首页搜索
      return(
        <View style={{flex:1}}>
          <View style={styles.searchView}>
            {this.renderIndexLab()}
            <SearchView  placeholder='输入电站名' val={this.state.hyName} 
              search={(val)=>this.searchFlowList(val,true)}/>
          </View>
          <RefreshListView
            style={{flex:1}}
            data={this.state.abnormalList}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderHomeItem}
            ItemSeparatorComponent={this._separator}
            refreshState={this.state.refreshState}
            onHeaderRefresh={this.onHeaderRefresh}
            onFooterRefresh={this.onFooterRefreshHome}
            // 可选
            footerRefreshingText= '数据加载中...'
            footerFailureText = '--数据加载失败--'
            footerNoMoreDataText= '--没有更多了--'
          />
        </View>
      ) 
    } else if(type == 1 || type == 2 || type == 3 || type == 4){
      return(
        <View style={{flex:1}}>
          <View style={styles.searchView}>
            {this.renderIndexLab()}
            <SearchView  placeholder='输入电站名' val={this.state.hyName} 
              search={(val)=>this.searchFlowList(val)}/>
          </View>
          <RefreshListView
            style={{flex:1}}
            data={this.state.abnormalList}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderFourItem}
            ItemSeparatorComponent={this._separator}
            refreshState={this.state.refreshState}
            onHeaderRefresh={this.onHeaderRefresh}
            onFooterRefresh={this.onFooterRefresh}
            // 可选
            footerRefreshingText= '数据加载中...'
            footerFailureText = '--数据加载失败--'
            footerNoMoreDataText= '--没有更多了--'
          />
        </View>
      )
    }else if(this.state.new){
      return(
        <Newest areaCode={this.state.areaCode} navigation={this.props.navigation}/>
      )
    }
  }
  _pressIndex(){
    dismissKeyboard()
    this.setState({type:0})
  }
  //渲染索引条
  renderIndexLab(){
    let type = this.state.type
    var desc = ''
    if(type == 1) desc = '数据异常'
    else if(type == 2) desc = '断流'
    else if(type == 3) desc = '未接入'
    else if(type == 4) desc = '正常'
    var view = null
    if(type >= 1 && type <= 4){
      view = <Text style={{color:'#00bfff'}}><Text style={{color:'#555'}}> > </Text>{desc}</Text>
    }
    return(
      <View style={{flexDirection:'row',alignItems:'center',paddingLeft:20,paddingTop:8,paddingBottom:5}}>
        <Text onPress={()=>{this._pressIndex()}}>实时监测</Text>
        {view}  
      </View>
    )
  }
  //渲染底部的两个按钮
  renderBottomView(){
    let isHistory = this. state.isHistory
    var image1
    var image2
    var textColor1
    var textColor2
    if(isHistory){
      image1 = require('../../images/monitor_time_icon_n.png')
      image2 = require('../../images/monitor_history_icon_y.png')
      textColor1 = {color:'#888',fontSize:14}
      textColor2 = {color:'#00bfff',fontSize:14}
    } else {
      image1 = require('../../images/monitor_time_icon_y.png')
      image2 = require('../../images/monitor_history_icon_n.png')
      textColor1 = {color:'#00bfff',fontSize:14}
      textColor2 = {color:'#888',fontSize:14}
    }
    var imgstyle = {marginRight:5}
    return(
      <View style={styles.bottomView}>
        <TouchableOpacity style={styles.button} onPress={()=>this.history(false)}>
          <Image style={imgstyle} source={image1}/>
          <Text style={textColor1}>实时监测</Text>
        </TouchableOpacity>
        <View style={{width:1,height:20,backgroundColor:'#aaa'}}></View>
        <TouchableOpacity style={styles.button} onPress={()=>this.history(true)}>
          <Image style={imgstyle} source={image2}/>
          <Text style={textColor2}>历史监测</Text>
        </TouchableOpacity>
      </View>
    )
  }
  render(){
    let headTime
    if(this.state.monitor.start_time){
      headTime = '('+this.state.monitor.start_time.substring(0,11)+'至'+this.state.monitor.end_time.substring(0,11)+')'
    }
    return(
      <View style={styles.container}>
        {!this.state.isHistory?
          <View style={{flex:1}} >
          <View style={styles.headerStyle}>
            <TouchableOpacity activeOpacity={0.5} style={[styles.topPadd,this.state.active24?styles.activeBor:null]} onPress={()=>this.isRecent(false)}>
              <Text style={[styles.headerText,this.state.active24?styles.active:null]}>24小时<Text style={styles.smallText}>{headTime}</Text></Text>
            </TouchableOpacity>
            <View style={[styles.line]}></View>
            <TouchableOpacity activeOpacity={0.5} style={[styles.topPadd,this.state.new?styles.activeBor:null]} onPress={()=>this.isRecent(true)}>
              <Text style={[styles.headerText,this.state.new?styles.active:null]} >最新</Text>
            </TouchableOpacity>
          </View>
          {this.renderMiddleList()}
        </View>:
          <History areaCode={this.state.areaCode} navigation={this.props.navigation}/>
        } 
        {this.renderBottomView()}
        <Toast ref="toast" position='bottom' positionValue={200}/>
      </View>
    )
  }
}
class Row extends Component{
  render(){
    return(
      <TouchableOpacity style={styles.row1} activeOpacity={0.5} onPress={this.props.press}>
        <View style={styles.leftView}>
          <Image source={this.props.image}/>
          <View style={styles.textView}>
            <Text>{this.props.title}</Text>
            <Text style={styles.grayText}>{this.props.desc}</Text>
          </View>
        </View>
        <View style={styles.rightView}>
          <Text style={[styles.numText,this.props.style]}>{this.props.num}座</Text>
          <Image source={require('../../images/arrow.png')}/>
        </View>
      </TouchableOpacity>
    )
  }
}
const styles = StyleSheet.create({
  button:{
    flexDirection:'row',
    alignItems:'center',
  },
  bottomView:{
    backgroundColor:'#fff',
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
    paddingTop:15,
    paddingBottom:isIphoneX()?30:15,
    borderTopWidth:StyleSheet.hairlineWidth,
    borderTopColor:'#aaa',
  },  
  
  numText:{
    marginRight:20,
  },  
  textView:{
    marginLeft:10,
  },  
  grayText:{
    color:'#999',
  },    
  splitView:{
    height:10,
    backgroundColor:'#f0f0f0',
  },
  leftView:{
    paddingLeft:30,
    flexDirection:'row',
    alignItems:'center',
  },
  rightView:{
    marginRight:20,
    flexDirection:'row',
    alignItems:'center',
  },
  row1:{
    paddingTop:10,
    paddingBottom:10,
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center',
  },  
  searchView:{
    backgroundColor:'#f0f0f0'
  },
  line:{
    width:1,
    height:20,
    backgroundColor:'#ccc',
  },
  topPadd:{
    paddingTop:15,
    paddingBottom:15,
  },
  activeBor:{
    borderBottomColor:'#32BDFF',
    borderBottomWidth:2,
  },
  active:{
    color:'#32BDFF',
  },
  headerText:{
    color:'#333',
    fontSize:16,
  },
  smallText:{
    fontSize:12,
  },
  headerStyle:{
    
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
  },  
  container:{
    flex:1,
  }
})